<template>
    <div class="page-container">
        <el-backtop :right="100" :bottom="100" ref="refBackTop" :visibility-height="100" target=".el-main"></el-backtop>
        <!-- 头部过滤部分 -->
        <div class="page-filter">
            <el-input v-model="filterProduct.title" placeholder="输入商品名称" clearable />
            <el-input v-model="filterProduct.barcode" placeholder="输入商品条形码" clearable />
            <el-select v-model="filterProduct.status" class="m-2" placeholder="选择商品状态" clearable>
                <el-option v-for="item in statusDic" :key="item.value" :label="item.name" :value="item.value" />
            </el-select>
            <el-cascader v-model="filterProduct.categoryId" placeholder="选择类目" :options="options" clearable
                :props="{ emitPath: false, value: 'id', label: 'title', children: 'childrenList' }" />
            <el-button type="primary" :icon="Search" @click="getProductList" >查找</el-button>
            <el-button type="primary" :icon="Plus" @click="handleCreatePage" v-permission="'product:product:create'">添加</el-button>
        </div>
        <!-- 数据列表 -->
        <div class="page-table">
            <el-table :data="productList" border style="width: 100%" v-loading="loading">
                <el-table-column type="selection" width="55" />
                <el-table-column type="expand" label="sku信息">
                    <template #default="props">
                        <div>
                            <el-table :data="props.row.skuList" border style="width: 100%">
                                <el-table-column prop="barCode" label="商品条码" />
                                <el-table-column prop="specification" label="商品规格" />
                                <el-table-column prop="stock" label="商品库存" />
                                <el-table-column prop="originalPrice" label="原价" />
                                <el-table-column prop="price" label="现价" />
                            </el-table>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column label="商品ID" prop="id" />
                <el-table-column label="名称" prop="title" width="200" />
                <el-table-column label="图片">
                    <template #default="scope">
                        <el-image style="width: 50px; height: 50px" :src="scope.row.img" fit="cover" />
                    </template>
                </el-table-column>
                <el-table-column label="商品详细介绍">
                    <template #default="scope">
                        <el-button type="primary" @click="handleSearchDetail(scope.row.id)">查看</el-button>
                    </template>
                </el-table-column>
                <el-table-column label="类目ID" prop="categoryId" />
                <el-table-column label="邮费模板ID" prop="freightTemplateId" />
                <el-table-column label="销量" prop="sales" />
                <el-table-column label="单位" prop="unit" />
                <el-table-column label="是否在售" prop="status">
                    <template #default="scope">
                        <el-tag type="success" v-if="scope.row.status === 1">在售</el-tag>
                        <el-tag type="warning" v-else>下架</el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="描述" prop="description" />
                <el-table-column label="操作">
                    <template #default="scope">
                        <el-button type="primary" @click="handleEditPage(scope.row.id)" v-permission="'product:product:edit'">编辑</el-button>
                        <el-button type="warning" v-if="scope.row.status === 1"
                            @click="handleChangeStatus(scope.row)">下架</el-button>
                        <el-button type="success" v-else @click="handleChangeStatus(scope.row)">在售</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <!-- 分页 -->
        <div style="overflow: hidden;">
            <Pagination v-bind="pagination" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </div>
        <!-- 查看商品详情对话框 -->
        <el-dialog v-model="dialogTableVisible" show-close title="商品详情">
            <div v-html="productDetail"></div>
        </el-dialog>
    </div>
</template>
<script lang="ts" setup>
import { post } from '@/utils/http'
import { nextTick, onMounted, reactive, ref } from 'vue';
import { ClassPagination, ClassProduct } from '#/index';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Plus, Search } from '@element-plus/icons-vue';
import { useRouter } from 'vue-router';

const router = useRouter()
//商品列表
const productList = ref([] as Array<ClassProduct>)
//分页对象
const pagination = reactive(new ClassPagination())
//回到顶部节点
const refBackTop = ref()
//过滤对象
const filterProduct = reactive({
    title: undefined,
    barcode: undefined,
    status: undefined,
    categoryId: undefined
})
//状态列表
const statusDic = [{ name: '下架', value: 0 }, { name: '在售', value: 1 }]
//类目
const options = ref()
//商品详情
const productDetail = ref('')
//商品对话框
const dialogTableVisible = ref(false)
//加载
const loading = ref(false)
/**
 * 生命周期请求数据
 */
onMounted(() => {
    getProductList()
    getCategory()
})

/**
 * 获取商品列表
 */
function getProductList() {
    const data = { _gp: 'admin.product', _mt: 'list', page: pagination.currentPage, limit: pagination.pageSize, ...filterProduct }
    post(data).then(res => {
        const { data, errno, errmsg } = res
        if (200 == errno) {
            const { items, total } = data
            productList.value = items
            pagination.total = total
            productList.value.forEach(item => {
                item.skuList.forEach(data => {
                    if (data.originalPrice && data.price) {
                        data.originalPrice *= 0.01
                        data.price *= 0.01
                    }
                })
            })
            nextTick(() => {
                refBackTop.value.$el.click?.()
            })
        } else {
            ElMessage.error(errmsg)
        }
    })
}
/**
 * 改变一页多少行,防止多次请求
 * @param value 一页多少行
 */
function handleSizeChange(value: number) {
    let tempCurrent = Math.ceil(pagination.total / value)
    if (tempCurrent < pagination.currentPage) {
        pagination.currentPage = tempCurrent
    }
    pagination.pageSize = value
    getProductList()
}

/**
 * 改变当前页
 * @param value 当前页数
 */
function handleCurrentChange(value: number) {
    pagination.currentPage = value
    getProductList()
}
/**
 * 获取分类树
 */
function getCategory() {
    loading.value = true
    const data = { _gp: 'admin.category', _mt: 'categoryTree' }
    post(data).then(res => {
        const { data, errno } = res
        if (200 === errno) {
            options.value = filterData(data)
        } else {
            ElMessage.error('获取分类失败')
        }
    })
    loading.value = false
}
/**
 * 过滤树数据，不能选择第二层
 * @param arr 数组
 */
function filterData(arr: []) {
    arr.forEach((item: any) => {
        if (item.childrenList) {
            filterData(item.childrenList)
        } else {
            if (item.level < 2) {
                item.disabled = true
            }
        }
    })
    return arr
}
/**
 * 查询商品详情
 * @param id 商品id
 */
function handleSearchDetail(id: number) {
    const data = { _gp: 'admin.product', _mt: 'detail', spuId: id }
    post(data).then(res => {
        console.log(res)
        const { errno, errmsg, data } = res
        if (200 === errno) {
            if (data.detail) {
                productDetail.value = data.detail.replace(/<img/ig, "<img style='width:100%' ")
                dialogTableVisible.value = true
            }
        } else {
            ElMessage.error(errmsg)
        }
    })
}
/**
 * 跳转到添加页面
 */
function handleCreatePage() {
    router.push({ name: 'createproduct' })
}
/**
 * 跳转到编辑页面
 * @param id 商品id
 */
function handleEditPage(id: number) {
    router.push(`/index/productmanage/editproduct/${id}`)
}
function handleChangeStatus(row: ClassProduct) {
    ElMessageBox.confirm(
        `此操作将改变${row.title}`,
        'Warning',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(() => {
        let status = row.status === 1 ? 0 : 1
        const data = { _gp: 'admin.product', _mt: 'freezeOrActivation', spuId: row.id, status }
        post(data).then(res => {
            const { errmsg, errno } = res
            if (200 === errno) {
                ElMessage.success('更改成功')
                getProductList()
            } else {
                ElMessage.error(errmsg)
            }
        })
    }).catch(() => {
        ElMessage({
            type: 'info',
            message: '取消更改',
        })
    })

}
</script>
<style lang="less" scoped>
.page-filter {
    display: flex;

    .el-input {
        margin-right: 10px;
        width: 200px;
    }

    .el-select {
        margin-right: 10px;
    }

    :deep(.el-cascader) {
        margin-right: 10px;
    }
}

:deep(#desc-module-1) {
    display: none;
}

// :deep(.el-dialog__body) {
//     padding: 0;
// }

// :deep(.el-dialog__header) {
//     display: none;
// }
</style>